package nickthissen.iracing.activities;

import java.util.ArrayList;

import nickthissen.iracing.adapters.PmListAdapter;
import nickthissen.iracing.common.Cache;
import nickthissen.iracing.common.DataLoader;
import nickthissen.iracing.common.ServiceLogging;
import nickthissen.iracing.common.Sharing;
import nickthissen.iracing.common.Task;
import nickthissen.iracing.datamodels.PrivateMessageItem;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.common.Error;
import nickthissen.iracing.iracingforum2.R;
import nickthissen.iracing.networking.Networking;
import nickthissen.iracing.parsing.Parser;
import nickthissen.iracing.parsing.PmListParser;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class PrivateMessageListActivity extends TaskItemListActivity<PrivateMessageItem>
{
    private ArrayList<PrivateMessageItem> messages;

    public static final int NEWPM = 1;

	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pmlist);

        this.getSupportActionBar().setTitle("Private Messages");

        this.loadData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getSupportMenuInflater().inflate(R.menu.pmlist, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) {
            case R.id.mnuPost:
                this.post();
                return true;
            case R.id.mnuRefresh:
                this.loadData();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected Task<?> createTask()
    {
        return new Task<Void>(this, loader);
    }

    @Override
    protected void saveTaskInput(Bundle state)
    {
    }

    @Override
    protected Object restoreTaskInput(Bundle state)
    {
        return null;
    }

    public static Intent getIntent(Context context)
	{
		Intent i = new Intent(context, PrivateMessageListActivity.class);
		return i;
	}

	@Override
	protected void setItems(ArrayList<PrivateMessageItem> items)
    {
        PmListAdapter adapter;
        if (this.getListAdapter() == null)
        {
            adapter = new PmListAdapter(this, R.layout.pmrow, items);
            this.setListAdapter(adapter);
        }
        else
        {
            adapter = (PmListAdapter) this.getListAdapter();
            adapter.clear();
            for (PrivateMessageItem item : items)
            {
                adapter.add(item);
            }
        }
	}

	@Override
	public void onItemClicked(PrivateMessageItem item)
    {
        Intent intent = PrivateMessageActivity.getIntent(this, item);
        this.startActivityForResult(intent, 0);
	}

	@Override
	protected void loadData()
    {
        boolean shouldLoadInBackground;
        ArrayList<PrivateMessageItem> cached = Cache.loadPms();
        if (cached != null)
        {
            messages = cached;
            setItems(messages);

            shouldLoadInBackground = true;
        }
        else
        {
            shouldLoadInBackground = false;
        }

		this.loadPmList(shouldLoadInBackground);
	}

    private void loadPmList(boolean background)
    {
        this.startLoading("Loading PMs...", null, background);
        ServiceLogging.logPageRequest(this, Networking.PMLIST_URL);
    }

    private void post()
    {
        Intent intent = SendPmActivity.getIntent(this, PostActivity.TYPE_SENDPM, null, null);
        this.startActivityForResult(intent, NEWPM);
    }

    private DataLoader<Void> loader = new DataLoader<Void>()
    {
        @Override
        public Result getData(Void in)
        {
            Result result = Networking.getPmInbox(this.getContext());
            if (result.Success)
            {
                String source = (String)result.Object;
                Parser parser = new PmListParser();
                return parser.parse(source);
            }
            else
            {
                return result;
            }
        }

        @Override
        public void onFinished(Result out)
        {
            if (out.Success)
            {
                messages = (ArrayList<PrivateMessageItem>)out.Object;
            }
            else
            {
                messages = new ArrayList<PrivateMessageItem>();
                Error.fromResult(out).report(this.getContext());
            }

            setItems(messages);
            Cache.savePms(messages);
            finishedLoading();
        }
    };
}
